<template>
  <div class="documentation">
    <el-container>
      <el-header>
        <h1>文档指南</h1>
        <el-menu mode="horizontal" router>
          <el-menu-item index="/">首页</el-menu-item>
          <el-menu-item index="/articles">文章列表</el-menu-item>
        </el-menu>
      </el-header>
      <el-container class="main-container">
        <!-- 左侧导航菜单 -->
        <el-aside width="250px" class="doc-sidebar">
          <el-menu
            :default-active="activeMenuItem"
            class="doc-menu"
            @select="handleMenuSelect"
            :default-openeds="['1']"
          >
            <template v-for="(group, index) in currentMenuConfig" :key="index">
              <el-sub-menu :index="String(index + 1)">
                <template #title>
                  <el-icon><Document /></el-icon>
                  <span>{{ group.title }}</span>
                </template>
                <el-menu-item
                  v-for="item in group.items"
                  :key="item.path"
                  :index="item.path"
                >
                  {{ item.label }}
                </el-menu-item>
              </el-sub-menu>
            </template>
          </el-menu>
        </el-aside>

        <!-- 中间文档内容区域 -->
        <el-main class="doc-content">
          <div class="markdown-body" v-html="renderedContent"></div>
        </el-main>

        <!-- 右侧目录导航 -->
        <el-aside width="200px" class="toc-sidebar">
          <div class="toc-container">
            <h3>目录</h3>
            <div class="toc-list" v-html="tocHtml"></div>
          </div>
        </el-aside>
      </el-container>
    </el-container>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, watch } from 'vue'
import { Document, Edit, Setting } from '@element-plus/icons-vue'
import MarkdownIt from 'markdown-it'
import anchor from 'markdown-it-anchor'
import hljs from 'highlight.js'
import 'highlight.js/styles/github.css'
import { useRoute, useRouter } from 'vue-router'

// 初始化markdown解析器
const md = new MarkdownIt({
  html: true,
  linkify: true,
  typographer: true,
  highlight: function (str, lang) {
    if (lang && hljs.getLanguage(lang)) {
      try {
        return hljs.highlight(str, { language: lang }).value
      } catch (__) {}
    }
    return '' // 使用默认的转义
  }
})

// 添加锚点插件
md.use(anchor, {
  permalink: true,
  permalinkBefore: true,
  permalinkSymbol: '#'
})

// 示例Markdown内容
const content = ref(`
# 文档标题

## 介绍
这是一个示例文档内容。

## 安装
安装步骤说明...

### 依赖项
列出相关依赖...

## 使用方法
使用说明...
`)

// 解析后的HTML内容
const renderedContent = ref('')

// 目录HTML
const tocHtml = ref('')

// 生成目录
const generateToc = (html: string) => {
  const headings = html.match(/<h([1-6]).*?>.*?<\/h\1>/g) || []
  let toc = ''
  let lastLevel = 0

  headings.forEach(heading => {
    const level = parseInt(heading.match(/<h([1-6])/)?.[1] || '1')
    const title = heading.replace(/<[^>]+>/g, '')
    const id = heading.match(/id="([^"]+)"/?.[1] || '')

    if (level > lastLevel) toc += '<ul>'
    else if (level < lastLevel) toc += '</ul>'.repeat(lastLevel - level)

    toc += `<li><a href="#${id}">${title}</a></li>`
    lastLevel = level
  })

  return toc
}

const route = useRoute()
const router = useRouter()

// 接收路由参数
const props = defineProps<{
  category?: string
  section?: string
}>()

// 当前激活的菜单项
const activeMenuItem = ref('')

// 根据category获取对应的菜单配置
const getMenuConfig = (category: string) => {
  // 这里可以根据不同的category返回不同的菜单配置
  const menuConfigs = {
    'guide': [
      {
        title: '快速开始',
        items: [
          { label: '入门介绍', path: '/docs/guide/intro' },
          { label: '环境搭建', path: '/docs/guide/setup' },
          { label: '第一个应用', path: '/docs/guide/first-app' }
        ]
      },
      {
        title: '基础教程',
        items: [
          { label: '基本概念', path: '/docs/guide/concepts' },
          { label: '项目结构', path: '/docs/guide/structure' },
          { label: '组件开发', path: '/docs/guide/components' }
        ]
      },
      {
        title: '进阶指南',
        items: [
          { label: '性能优化', path: '/docs/guide/optimization' },
          { label: '最佳实践', path: '/docs/guide/best-practices' },
          { label: '部署指南', path: '/docs/guide/deployment' }
        ]
      }
    ],
    'java': [
      {
        title: '基础知识',
        items: [
          { label: 'Java基础', path: '/docs/java/basic' },
          { label: '面向对象', path: '/docs/java/oop' },
          { label: '集合框架', path: '/docs/java/collection' }
        ]
      },
      {
        title: '高级特性',
        items: [
          { label: '多线程编程', path: '/docs/java/thread' },
          { label: 'IO与网络', path: '/docs/java/io' },
          { label: 'JVM原理', path: '/docs/java/jvm' }
        ]
      },
      {
        title: '框架技术',
        items: [
          { label: 'Spring全家桶', path: '/docs/java/spring' },
          { label: 'MyBatis', path: '/docs/java/mybatis' },
          { label: 'Netty', path: '/docs/java/netty' }
        ]
      }
    ],
    'database': [
      {
        title: '关系型数据库',
        items: [
          { label: 'MySQL基础', path: '/docs/database/mysql-basic' },
          { label: 'MySQL高级特性', path: '/docs/database/mysql-advanced' },
          { label: 'MySQL性能优化', path: '/docs/database/mysql-optimization' }
        ]
      },
      {
        title: 'NoSQL数据库',
        items: [
          { label: 'Redis基础', path: '/docs/database/redis-basic' },
          { label: 'Redis高级特性', path: '/docs/database/redis-advanced' },
          { label: 'MongoDB基础', path: '/docs/database/mongodb-basic' }
        ]
      },
      {
        title: '数据库设计',
        items: [
          { label: '设计理论', path: '/docs/database/design-theory' },
          { label: '最佳实践', path: '/docs/database/design-practice' },
          { label: '分库分表', path: '/docs/database/sharding' }
        ]
      }
    ],
    'middleware': [
      {
        title: '消息队列',
        items: [
          { label: 'Kafka', path: '/docs/middleware/kafka' },
          { label: 'RabbitMQ', path: '/docs/middleware/rabbitmq' },
          { label: 'RocketMQ', path: '/docs/middleware/rocketmq' }
        ]
      },
      {
        title: '缓存技术',
        items: [
          { label: 'Redis缓存', path: '/docs/middleware/redis-cache' },
          { label: 'Memcached', path: '/docs/middleware/memcached' },
          { label: '缓存策略', path: '/docs/middleware/cache-strategy' }
        ]
      },
      {
        title: 'API网关',
        items: [
          { label: 'Nginx', path: '/docs/middleware/nginx' },
          { label: 'Spring Cloud Gateway', path: '/docs/middleware/spring-cloud-gateway' },
          { label: 'Zuul', path: '/docs/middleware/zuul' }
        ]
      }
    ],
    'distributed': [
      {
        title: '分布式基础',
        items: [
          { label: '分布式理论', path: '/distributed/basic/theory' },
          { label: '一致性协议', path: '/distributed/basic/consensus' },
          { label: '分布式事务', path: '/distributed/basic/transaction' }
        ]
      },
      {
        title: '微服务架构',
        items: [
          { label: '服务注册与发现', path: '/distributed/microservice/discovery' },
          { label: '负载均衡', path: '/distributed/microservice/loadbalance' },
          { label: '服务熔断与降级', path: '/distributed/microservice/circuit-breaker' }
        ]
      }
    ]
  }
  return menuConfigs[category as keyof typeof menuConfigs] || []
}

// 当前菜单配置
const currentMenuConfig = ref([])

// 处理菜单选择
const handleMenuSelect = (index: string) => {
  router.push(index)
}

// 加载文档内容
const loadDocContent = (section: string) => {
  // 这里可以根据section参数加载对应的文档内容
  // 实际应用中，这里应该从后端API获取文档内容
  content.value = `# ${section.charAt(0).toUpperCase() + section.slice(1)}

## 介绍
这是${section}的文档内容。

## 详细说明
具体的文档内容将从后端获取。
`
  renderedContent.value = md.render(content.value)
  tocHtml.value = generateToc(renderedContent.value)
}

// 监听路由变化
watch(
  () => route.path,
  (path) => {
    const pathSegments = path.split('/')
    const category = pathSegments[2] // 获取路由中的category部分
    if (category) {
      // 更新左侧菜单配置
      currentMenuConfig.value = getMenuConfig(category)
      // 更新当前激活的菜单项
      activeMenuItem.value = path
      // 加载文档内容
      const currentSection = pathSegments[3] || ''
      loadDocContent(currentSection)

      // 找到当前路径对应的菜单项并展开对应的菜单组
      const menuConfig = getMenuConfig(category)
      menuConfig.forEach((group, groupIndex) => {
        const matchedItem = group.items.find(item => item.path === path)
        if (matchedItem) {
          // 展开对应的子菜单
          const el = document.querySelector(`.el-sub-menu[index="${groupIndex + 1}"]`)
          if (el) {
            const submenu = (el as any).__vueParentComponent?.proxy
            if (submenu?.open) submenu.open()
          }
        }
      })
    }
  },
  { immediate: true }
)

// 组件挂载时初始化内容
onMounted(() => {
  renderedContent.value = md.render(content.value)
  tocHtml.value = generateToc(renderedContent.value)
})
</script>

<style scoped>
.documentation {
  height: 100vh;
  background: rgba(255, 255, 255, 0.9);
  backdrop-filter: blur(10px);
}

.main-container {
  height: calc(100vh - 60px);
}

.doc-sidebar {
  background: rgba(255, 255, 255, 0.95);
  border-right: 1px solid #eee;
  height: 100%;
  overflow-y: auto;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  backdrop-filter: blur(10px);
  transition: all 0.3s ease;
}

:deep(.doc-menu) {
  border-right: none;
}

:deep(.doc-menu .el-sub-menu__title),
:deep(.doc-menu .el-menu-item) {
  height: 45px;
  line-height: 45px;
  padding-right: 8px !important;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  transition: all 0.3s ease;
}

:deep(.doc-menu .el-sub-menu .el-menu-item) {
  min-width: auto;
  padding-left: 40px !important;
}

:deep(.doc-menu .el-menu-item:hover),
:deep(.doc-menu .el-sub-menu__title:hover) {
  background-color: rgba(64, 158, 255, 0.1);
  color: #409EFF;
}

.doc-content {
  padding: 20px 40px;
  height: 100%;
  overflow-y: auto;
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(10px);
}

.toc-sidebar {
  background: rgba(255, 255, 255, 0.95);
  border-left: 1px solid #eee;
  padding: 20px;
  height: 100%;
  overflow-y: auto;
  width: 280px !important;
  box-shadow: -2px 0 12px 0 rgba(0, 0, 0, 0.1);
  backdrop-filter: blur(10px);
  transition: all 0.3s ease;
}

.toc-container {
  position: sticky;
  top: 20px;
}

.toc-list {
  font-size: 14px;
}

.toc-list ul {
  list-style: none;
  padding-left: 15px;
  margin: 0;
}

.toc-list li {
  margin: 8px 0;
}

.toc-list a {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  display: block;
  padding: 4px 8px;
  border-radius: 4px;
  transition: all 0.3s ease;
  color: #666;
  text-decoration: none;
}

.toc-list a:hover {
  background-color: rgba(64, 158, 255, 0.1);
  color: #409EFF;
  text-decoration: none;
  transform: translateX(4px);
}

/* Markdown样式 */
.markdown-body {
  font-size: 16px;
  line-height: 1.6;
  color: #24292e;
}

.markdown-body h1 {
  font-size: 2em;
  border-bottom: 1px solid #eaecef;
  padding-bottom: 0.3em;
}

.markdown-body h2 {
  font-size: 1.5em;
  border-bottom: 1px solid #eaecef;
  padding-bottom: 0.3em;
}

.markdown-body h3 {
  font-size: 1.25em;
}

.markdown-body p {
  margin: 1em 0;
}

.markdown-body ul,
.markdown-body ol {
  padding-left: 2em;
  margin: 1em 0;
}

.markdown-body blockquote {
  margin: 1em 0;
  padding: 0 1em;
  color: #6a737d;
  border-left: 0.25em solid #dfe2e5;
}

.markdown-body img {
  max-width: 100%;
  height: auto;
}

.markdown-body table {
  border-spacing: 0;
  border-collapse: collapse;
  width: 100%;
  margin: 1em 0;
}

.markdown-body table th,
.markdown-body table td {
  padding: 6px 13px;
  border: 1px solid #dfe2e5;
}

.markdown-body table tr {
  background-color: #fff;
  border-top: 1px solid #c6cbd1;
}

.markdown-body table tr:nth-child(2n) {
  background-color: #f6f8fa;
}

.markdown-body hr {
  height: 0.25em;
  padding: 0;
  margin: 24px 0;
  background-color: #e1e4e8;
  border: 0;
}

.markdown-body h1,
.markdown-body h2,
.markdown-body h3 {
  margin-top: 24px;
  margin-bottom: 16px;
  font-weight: 600;
  line-height: 1.25;
}

.markdown-body code {
  background-color: rgba(27, 31, 35, 0.05);
  border-radius: 3px;
  padding: 0.2em 0.4em;
  font-size: 85%;
}

.markdown-body pre {
  background-color: rgba(246, 248, 250, 0.95);
  border-radius: 3px;
  padding: 16px;
  overflow: auto;
  backdrop-filter: blur(10px);
}
</style>